package org.datacoder.geocoding.jurisdiction

import org.datacoder.util.*

class MunicipalityService {

    def jurisdictionService
    def stateService
    def userService

    static transactional = true

    /* CRUD */
    public Municipality create(Municipality munic) throws DAOException{
        save(munic)
        return munic
    }
    public void save(Municipality munic) throws DAOException{
        ServiceUtils.save(munic)
    }
    public void save(Municipality munic, boolean flush) throws DAOException{
        ServiceUtils.save(munic, flush)
    }
    public void delete(Municipality munic){
        if(munic == null){
            return
        }
        munic.delete(flush:true)
    }
    public Municipality merge(Municipality munic){
        return munic.merge()
    }
    public Municipality get(String municId){
        return get(Long.parseLong(municId))
    }
    public Municipality get(long municId){
        return Municipality.get(municId)
    }
    public Set<Municipality> getAll(){
        return Municipality.findAll()
    }
    /* END CRUD */

    public Municipality getByNameAndStateOrCreate(String name, State state, String longName){
        Municipality munic = getByNameAndState(name, state)
        if(munic == null){
            munic = new Municipality(
                name:name,
                longName:longName,
                state:state
            )
            munic = create(munic)
        }
        return munic
    }

    public Municipality getByNameAndState(String name, State state){
        Municipality munic = Municipality.findByNameAndState(name, state)
        return munic
    }

    public Set<Municipality> getByStateAndPrefix(State state, String prefix) {
        return Municipality.findAllByStateAndNameIlike(state, prefix + "%")
    }
}

